package fzdy.tools;


import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.*;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * Created by Administrator on 2017/5/20 0020.
 */
public class HttpTool {
    /**
     * 主动发送消息
     * @param mess
     * @return
     */
    public static JSONObject sendReqMsg(String mess,String url){
        //消息json格式
        //System.out.println(jsonContext);
        JSONObject responseBody = null;
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httpPost= new HttpPost(url);
//            HttpPost httpPost= new HttpPost("https://qyapi.weixin.qq.com/cgi-bin/message/send");
            //发送json格式的数据
            StringEntity myEntity = new StringEntity(mess, ContentType.create("application/json", "UTF-8"));
            //设置需要传递的数据
            httpPost.setEntity(myEntity);
            // Create a custom response handler
            ResponseHandler<JSONObject> responseHandler = new ResponseHandler<JSONObject>() {
                //对访问结果进行处理
                public JSONObject handleResponse(
                        final HttpResponse response) throws ClientProtocolException, IOException {
                    int status = response.getStatusLine().getStatusCode();
                    if (status >= 200 && status < 300) {
                        HttpEntity entity = response.getEntity();
                        if(null!=entity){
                            String result= EntityUtils.toString(entity);
                            //根据字符串生成JSON对象
                            return JSONObject.parseObject(result);
                        }else{
                            return null;
                        }
                    } else {
                        throw new ClientProtocolException("Unexpected response status: " + status);
                    }
                }

            };
            //返回的json对象
            responseBody = httpclient.execute(httpPost, responseHandler);
//            int result= (Integer) responseBody.get("errcode");
            httpclient.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return responseBody;
    }
}
